<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false">
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleAddSubmit" :form="form">
        <a-form-item
          label="添加模式"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-tag color="#428bca" @click="checkMode()" v-if="!this.check">切换为扫码模式</a-tag>
          <a-tag color="#428bca" @click="checkMode()" v-else>切换为选择模式</a-tag>
        </a-form-item>
        <a-form-item
          label="商品"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
          v-if="!this.check"
        >
          <a-select
            show-search
            :value="value ? value : undefined"
            :placeholder="`请至少输入一个字符`"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="handleSearch"
            @change="handleChange"
          >
            <a-select-option v-for="d in goodsoption" :key="d.inventoryId">
              {{ d.goodName }} {{ d.phoneCode1 }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="串码"
          v-else
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-textarea
            rows="8"
            placeholder="可添加多个,每行一个串码，错误的串码会被过滤掉"
            v-decorator="['phoneCodeList', { rules: [{ required: true, message: '请输入' }] }]"
          />
        </a-form-item>
        <a-form-item
          label="出库价格"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-input-number
            style="width: 100%"
            v-decorator="['outPrice', { rules: [{ required: true, message: '请输入' }] }]"
          />
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">添加</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" title="出库商品清单">
      <template #extra>
        <a-tooltip>
          <template #title> {{ `${isMx? '切换明细':'切换汇总'} ` }}</template>
          <a-button type="primary" icon="swap" @click="handleAdd(queryParam)"></a-button>
        </a-tooltip> 
      </template>
      <!-- <a-button class="editable-add-btn" @click="handleAdd" >{{ this.isMx ? '切换汇总' :'切换明细' }} </a-button> -->
      <a-table size="default" rowKey="key" :columns="this.isMx ? mxColumns : columns" :data-source="this.isMx ? loadData : hzLoadData">
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="total" slot-scope="text, record">
          <template>
            {{ record.num * record.outPrice }}
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428BCA" @click="handleEdit(record)">编辑</a-tag>
            <a-tag color="#D15B47" @click="handleDel(record)">删除</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card :body-style="{ padding: '24px 32px' }" :bordered="false">
      <a-form @submit="handleSubmit" :form="submitform">
        <a-form-item
          label="经销商"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select v-decorator="['supplyId',{ rules: [{ required: true, message: '请选择' }] }]" placeholder="请选择经销商">
            <a-select-option :value="i.id" v-for="i in supplyoption" :key="i.id">{{ i.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="销售业务"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-select v-decorator="['empId',{ rules: [{ required: true, message: '请选择' }] }]" placeholder="请选择">
            <a-select-option :value="i.id" v-for="i in useroption" :key="i.id">{{ i.userName }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="出库日期"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-date-picker v-decorator="['outDate',{ initialValue:this.toDays, rules: [{ required: true, message: '请选择' }]}]" valueFormat="YYYY-MM-DD"/>
        </a-form-item>
        <a-form-item
          label="备注"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }"
        >
          <a-input v-decorator="['memo']" placeholder="请输入备注" />
        </a-form-item>
        <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button htmlType="submit" type="primary" icon="check">提交出库</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
      <price-form
        ref="priceModal"
        :visible="priceVisible"
        :loading="priceLoading"
        :model="priceMdll"
        @cancel="handlePriceCancel"
        @ok="handlePriceOk"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { addWholesaleUsingPOST, getInventoryListUsingGET ,getInventoryListByPhoneCdeUsingGET} from '@/api/api/pifayewu.ts'
import { getEmployeesListUsingPOST } from '@/api/api/yuangongguanli.ts'
import { getSuppliesListUsingPOST } from '@/api/api/jingxiaoshangyunyingshangguanli.ts'
import moment from 'moment'
import PriceForm from './PriceForm'
export default {
  name: 'WholesaleSellShop',
  components: {
    PriceForm
  },
  data() {
    return {
      check: false,
      isMx:false,
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      priceVisible: false,
      priceLoading: false,
      priceMdll: null,
      value:undefined,
      toDays: moment().format('YYYY-MM-DD'),
      form: this.$form.createForm(this),
      submitform: this.$form.createForm(this),
      columns: [
        {
          title: '商品',
          dataIndex: 'goodName',
        },
        {
          title: '成本(元)',
          dataIndex: 'commCost',
        },
        {
          title: '单价(元)',
          dataIndex: 'outPrice',
        },
        {
          title: '数量',
          dataIndex: 'num',
        },
        {
          title: '合计(元)',
          dataIndex: 'total',
          scopedSlots: { customRender: 'total' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' }
          }
      ],
      mxColumns:[
        {
          title: '商品',
          dataIndex: 'goodName',
        },
        {
          title: '串码',
          dataIndex: 'phoneCode1',
        },
        {
          title: '串码2',
          dataIndex: 'phoneCode2',
        },
        {
          title: '供应商',
          dataIndex: 'supplyName',
        },
        {
          title: '成本(元)',
          dataIndex: 'commCost',
        },
        {
          title: '出库价(元)',
          dataIndex: 'outPrice',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' }
          }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: [],
      hzLoadData: [],
      nameList:[],
      outPriceList:[],
      goodsoption: [],
      supplyoption: [],
      useroption: [],
      optionParam: {
        pageNo: 1,
        pageSize: 999,
        queryCondition: '',
        status: 1,
      },
    }
  },
  mounted() {
    // this.getGoodsOption({ ...this.optionParam })
    this.getSupOption()
    this.getUserOption()
  },
  methods: {
    handleAdd(){
      this.isMx = !this.isMx
    },
    handleEdit(record) {
      this.priceVisible = true
      this.priceMdll = record
    },
    handlePriceCancel() {
      this.priceVisible = false
      const form = this.$refs.priceModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handlePriceOk() {
      const form = this.$refs.priceModal.form
      this.priceLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          // 修改 e.g.
         this.loadData = this.loadData.map(item => {
            return {
              ...item,
              outPrice: values.outPrice
            }
          })
          this.priceLoading = false
          this.priceVisible = false
        } else {
          this.priceLoading = false
          this.priceVisible = false
        }
      })
    },
    handleDel(record){
      const that = this
      that.$confirm({
        title: '删除',
        content: '你确定要删除这个商品吗？',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          if(that.isMx){
            that.loadData.splice( that.loadData.findIndex(item => item.id === record.id), 1)
          }else{
            that.hzLoadData.splice( that.hzLoadData.findIndex(item => item.id === record.id), 1)
          }
          that.nameList = that.loadData.map(item => item.goodName)
          const outPriceObj = {}
          that.loadData.forEach(v => outPriceObj[v.goodName] = outPriceObj[v.goodName] === undefined ? v.outPrice : outPriceObj[v.goodName] + v.outPrice)
          const myObj = that.getRepeatNum()
          that.hzLoadData = that.hzLoadData.map((item)=>{
            return {
              ...item,
              num:myObj[item.goodName],
              outPrice:(outPriceObj[item.goodName] / myObj[item.goodName]).toFixed(2)
            }
          })
        },
      })
    },
    handleSearch(value) {
      this.getGoodsOption(value)
    },
    handleChange(value) {
      this.value = value
    },
    getGoodsOption(params) {
      getInventoryListByPhoneCdeUsingGET({...this.optionParam,storeId: this.$route.params.id,phoneCodeStr:params})
        .then((res) => {
          this.goodsoption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    getSupOption() {
      getSuppliesListUsingPOST({ ...this.optionParam, typesList: '2,3' })
        .then((res) => {
          this.supplyoption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    getUserOption() {
      getEmployeesListUsingPOST(this.optionParam)
        .then((res) => {
          this.useroption = res.data.list
        })
        .catch((error) => {
          this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
        })
    },
    checkMode() {
      this.check = !this.check
    },
    removeTrim(array) {
      for (let i = 0; i < array.length; i++) {
        if (array[i] == '') {
          array.splice(i, 1)
          i = i - 1
        }
      }
      return array
    },
    getRepeatNum(){
      return this.nameList.reduce((prev,next)=>{
        prev[next] = (prev[next] + 1) || 1
        return prev
      },{})
    },
    handleAddSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.check) {
            getInventoryListUsingGET({ pageNo: 1, pageSize: 999, storeId: this.$route.params?.id, status: 1, phoneCodeList: this.removeTrim(values.phoneCodeList.split('\n')).toString() })
              .then((res) => {
                const data = res.data.list.map((item) => {
                  return {
                    ...item,
                    outPrice: values.outPrice,
                  }
                })
                const includes = this.loadData.some((i) => data?.map((j) => j.phoneCode1)?.includes(i.phoneCode1))
                if (!!includes) {
                  this.$message.error('存在相同串码')
                } else {
                  this.loadData = this.loadData.concat(data)
                  this.hzLoadData = this.loadData.concat(data)
                }
              })
              .catch((error) => {
                this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
              })
          } else {
            const includes = this.loadData
              .map((item) => item.phoneCode1)
              .includes(
                this.goodsoption.find((item) => {
                return item.inventoryId == this.value
              }).phoneCode1
              )
            if (!!includes) {
              this.$message.error('存在相同串码')
              return false
            }
            this.loadData.push({
              ...values,
              num:1,
              outPrice:values.outPrice,
              commCost: this.goodsoption.find((item) => {
                return item.inventoryId == this.value
              }).commCost,
              inventoryId:this.goodsoption.find((item) => {
                return item.inventoryId == this.value
              }).inventoryId,
              phoneCode1: this.goodsoption.find((item) => {
                return item.inventoryId == this.value
              }).phoneCode1,
              goodName: this.goodsoption.find((item) => {
                return item.inventoryId == this.value
              }).goodName,
              phoneCode1: this.goodsoption.find((item) => {
                return item.inventoryId == this.value
              }).phoneCode1,
              phoneCode2: this.goodsoption.find((item) => {
                return item.inventoryId == this.value
              }).phoneCode2,
              supplyName: this.goodsoption.find((item) => {
                return item.inventoryId == this.value
              }).supplyName,
            })
            
            for (var i = 0; i < this.loadData.length; i++) {
                var obj = {
                  commCost: this.loadData[i].commCost,
                  inventoryId: this.loadData[i].inventoryId,
                  outPrice: this.loadData[i].outPrice,
                  phoneCode1: this.loadData[i].phoneCode1,
                  goodName: this.loadData[i].goodName,
                  num: this.loadData[i].num ?? 0,
                }
                this.hzLoadData.push(obj)
            }
            this.hzLoadData = this.hzLoadData.filter((item, index) =>this.hzLoadData.findIndex(i => i.goodName === item.goodName) === index)
            this.nameList = this.loadData.map(item => item.goodName)
            // this.outPriceList = this.loadData.map(item => item.outPrice)
            const outPriceObj = {}
            this.loadData.forEach(v => outPriceObj[v.goodName] = outPriceObj[v.goodName] === undefined ? v.outPrice : outPriceObj[v.goodName] + v.outPrice)
            const myObj = this.getRepeatNum()
            this.hzLoadData = this.hzLoadData.map((item)=>{
              return {
                ...item,
                num:myObj[item.goodName],
                outPrice:(outPriceObj[item.goodName] / myObj[item.goodName]).toFixed(2)
              }
            })
          }
        }
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.submitform.validateFields((err, values) => {
        if (!err) {
          if(this.loadData.length == 0) {
            this.$message.error('没有可出库的商品')
            return false
          }
    
          addWholesaleUsingPOST(
            {
              ...values,
              outDate: values?.outDate,
              storeId: this.$route.params.id,
            },
            this.isMx ? this.loadData : this.hzLoadData
          )
            .then((res) => {
              this.$message.success('操作成功')
              this.$router.push({ path: `/wholesale/sellrecord/detail/${res.data.id}` })
              // 重置表单数据
              this.form.resetFields()
              this.submitform.resetFields()
            })
            .catch((error) => {
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        }
      })
    },
  },
}
</script>
